package legumes.client.ui.widgets.form.item;

import legumes.client.services.callbacks.GetProductVaritiesCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.shared.domain.ProductVariety;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;

public class ProductVarietytFormItem extends ComboBoxItem {
	
	private ProductVariety pv;
	private ProductVariety [] pvAr;
	
	public ProductVarietytFormItem(String initValue_){
		super("ProductVariety", "Vari&eacute;t&eacute;");
		setWidth("70");
		setTextAlign(Alignment.LEFT);
		setValidators(new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				ProductVariety pvFound = findProductVariety(value.toString());
				pv = pvFound;
				return pv != null;
			}
			
		});
		setValidateOnExit(true);
        initComboMap();
	}
	
	public ProductVariety findProductVariety(String productVariety_){
		for(ProductVariety pv : pvAr){
			if(pv.getName().equalsIgnoreCase(productVariety_)){
				return pv;
			}
		}
		return null;
	}
	
	private void initComboMap() {
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final GetProductVaritiesCallback getProductVaritiesCallback = new GetProductVaritiesCallback();
		callSequencer.addCall(getProductVaritiesCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				pvAr = getProductVaritiesCallback.getProductVarities();
				String [] str = new String[pvAr.length];
				int i=0;
				for( ProductVariety pv : pvAr){
					str[i] = pv.getName();
					i++;
				}
				setValueMap(str);
			}
		});
		callSequencer.callSequence();
	}

	public ProductVariety getProductVariety(){
		return pv;
	}
	
}
